using DocumentCreationSystem.Helpers;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 数据清理对话框
    /// </summary>
    public partial class DataCleanupDialog : Window
    {
        private readonly DataCleanupService _cleanupService;
        private readonly ILogger<DataCleanupDialog> _logger;
        private bool _isProcessing = false;

        public DataCleanupDialog()
        {
            InitializeComponent();

            // 从依赖注入容器获取服务
            var app = (App)Application.Current;
            var serviceProvider = App.ServiceProvider;
            
            var dataStorage = serviceProvider.GetRequiredService<IDataStorageService>();
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            
            _cleanupService = new DataCleanupService(dataStorage, loggerFactory.CreateLogger<DataCleanupService>());
            _logger = loggerFactory.CreateLogger<DataCleanupDialog>();
        }

        private async void CheckIntegrityButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isProcessing) return;

            try
            {
                _isProcessing = true;
                SetUIState(false);
                
                _logger.LogInformation("开始检查数据完整性...");
                
                var report = await _cleanupService.GetDataIntegrityReportAsync();
                
                IntegrityResultText.Visibility = Visibility.Visible;
                
                if (report.IsValid && !report.HasAnyIssues)
                {
                    IntegrityResultText.Text = "✅ 数据完整性检查通过，未发现问题。";
                    IntegrityResultText.Foreground = System.Windows.Media.Brushes.Green;
                }
                else if (!string.IsNullOrEmpty(report.ErrorMessage))
                {
                    IntegrityResultText.Text = $"❌ 检查失败: {report.ErrorMessage}";
                    IntegrityResultText.Foreground = System.Windows.Media.Brushes.Red;
                }
                else
                {
                    var issues = new List<string>();
                    
                    if (report.OrphanedDocuments.Count > 0)
                        issues.Add($"孤立文档: {report.OrphanedDocuments.Count} 个");
                    if (report.OrphanedNovelProjects.Count > 0)
                        issues.Add($"孤立小说项目: {report.OrphanedNovelProjects.Count} 个");
                    if (report.OrphanedChapters.Count > 0)
                        issues.Add($"孤立章节: {report.OrphanedChapters.Count} 个");
                    if (report.OrphanedCharacters.Count > 0)
                        issues.Add($"孤立角色: {report.OrphanedCharacters.Count} 个");
                    if (report.OrphanedVectorRecords.Count > 0)
                        issues.Add($"孤立向量记录: {report.OrphanedVectorRecords.Count} 个");
                    if (report.OrphanedWorldSettings.Count > 0)
                        issues.Add($"孤立世界设定: {report.OrphanedWorldSettings.Count} 个");
                    if (report.DuplicateProjectIds.Count > 0)
                        issues.Add($"重复项目ID: {report.DuplicateProjectIds.Count} 个");
                    if (report.DuplicateDocumentIds.Count > 0)
                        issues.Add($"重复文档ID: {report.DuplicateDocumentIds.Count} 个");
                    if (report.DuplicateNovelProjectIds.Count > 0)
                        issues.Add($"重复小说项目ID: {report.DuplicateNovelProjectIds.Count} 个");
                    
                    IntegrityResultText.Text = $"⚠️ 发现 {report.TotalIssuesCount} 个问题:\n{string.Join("\n", issues)}";
                    IntegrityResultText.Foreground = System.Windows.Media.Brushes.Orange;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查数据完整性失败");
                IntegrityResultText.Visibility = Visibility.Visible;
                IntegrityResultText.Text = $"❌ 检查失败: {ex.Message}";
                IntegrityResultText.Foreground = System.Windows.Media.Brushes.Red;
            }
            finally
            {
                _isProcessing = false;
                SetUIState(true);
            }
        }

        private async void StartCleanupButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isProcessing) return;

            var result = MessageBox.Show(
                "确定要开始清理数据库吗？\n\n此操作将删除所有无效的数据引用。\n建议在清理前创建备份。",
                "确认清理",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes) return;

            try
            {
                _isProcessing = true;
                SetUIState(false);
                
                _logger.LogInformation("开始执行数据清理...");

                var options = new DataCleanupOptions
                {
                    CleanOrphanedDocuments = CleanDocumentsCheckBox.IsChecked == true,
                    CleanOrphanedNovelProjects = CleanNovelProjectsCheckBox.IsChecked == true,
                    CleanOrphanedChapters = CleanChaptersCheckBox.IsChecked == true,
                    CleanOrphanedCharacters = CleanCharactersCheckBox.IsChecked == true,
                    CleanOrphanedVectorRecords = CleanVectorRecordsCheckBox.IsChecked == true,
                    CleanOrphanedWorldSettings = CleanWorldSettingsCheckBox.IsChecked == true,
                    CreateBackup = CreateBackupCheckBox.IsChecked == true
                };

                var cleanupResult = await _cleanupService.PerformFullCleanupAsync(options);
                
                ShowCleanupResult(cleanupResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据清理失败");
                MessageBox.Show($"清理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isProcessing = false;
                SetUIState(true);
            }
        }

        private async void CreateBackupButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isProcessing) return;

            try
            {
                _isProcessing = true;
                SetUIState(false);
                
                _logger.LogInformation("创建数据备份...");
                
                var backup = await _cleanupService.CreateBackupAsync("手动创建的备份");
                
                BackupStatusText.Visibility = Visibility.Visible;
                
                if (backup != null)
                {
                    BackupStatusText.Text = $"✅ 备份创建成功: {backup.BackupPath}\n大小: {backup.BackupSize / 1024.0:F1} KB";
                    BackupStatusText.Foreground = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    BackupStatusText.Text = "❌ 备份创建失败";
                    BackupStatusText.Foreground = System.Windows.Media.Brushes.Red;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建备份失败");
                BackupStatusText.Visibility = Visibility.Visible;
                BackupStatusText.Text = $"❌ 备份创建失败: {ex.Message}";
                BackupStatusText.Foreground = System.Windows.Media.Brushes.Red;
            }
            finally
            {
                _isProcessing = false;
                SetUIState(true);
            }
        }

        private async void ViewBackupsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var backups = await _cleanupService.GetBackupListAsync();
                
                if (backups.Count == 0)
                {
                    MessageHelper.ShowInformation(
                        "没有找到备份文件。",
                        "备份列表",
                        "系统中暂时没有数据备份文件。当您执行数据清理操作时，系统会自动创建备份。",
                        this);
                    return;
                }

                var message = "备份文件列表:\n\n";
                foreach (var backup in backups.Take(10)) // 只显示最近10个
                {
                    message += $"{backup.CreatedAt:yyyy-MM-dd HH:mm:ss} - {backup.BackupSize / 1024.0:F1} KB\n";
                    message += $"  {System.IO.Path.GetFileName(backup.BackupPath)}\n\n";
                }

                var details = message;
                if (backups.Count > 10)
                {
                    details += $"... 还有 {backups.Count - 10} 个备份文件";
                }

                MessageHelper.ShowInformation(
                    $"找到 {backups.Count} 个备份文件",
                    "备份列表",
                    details,
                    this);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查看备份列表失败");
                MessageBox.Show($"查看备份失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void CleanOldBackupsButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(
                "确定要清理30天前的旧备份文件吗？",
                "确认清理",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes) return;

            try
            {
                var deletedCount = await _cleanupService.CleanupOldBackupsAsync(30);
                MessageBox.Show($"已清理 {deletedCount} 个旧备份文件。", "清理完成", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理旧备份失败");
                MessageBox.Show($"清理失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SetUIState(bool enabled)
        {
            CheckIntegrityButton.IsEnabled = enabled;
            StartCleanupButton.IsEnabled = enabled;
            CreateBackupButton.IsEnabled = enabled;
            ViewBackupsButton.IsEnabled = enabled;
            CleanOldBackupsButton.IsEnabled = enabled;
            
            ProgressBar.Visibility = enabled ? Visibility.Collapsed : Visibility.Visible;
        }

        private void ShowCleanupResult(DataCleanupResult result)
        {
            ResultGroupBox.Visibility = Visibility.Visible;
            
            if (result.IsSuccess)
            {
                CleanupResultText.Text = $"✅ {result.Message}";
                CleanupResultText.Foreground = System.Windows.Media.Brushes.Green;
                
                var details = new List<string>();
                
                if (result.RemovedDocumentsCount > 0)
                    details.Add($"清理了 {result.RemovedDocumentsCount} 个孤立文档");
                if (result.RemovedNovelProjectsCount > 0)
                    details.Add($"清理了 {result.RemovedNovelProjectsCount} 个孤立小说项目");
                if (result.RemovedChaptersCount > 0)
                    details.Add($"清理了 {result.RemovedChaptersCount} 个孤立章节");
                if (result.RemovedCharactersCount > 0)
                    details.Add($"清理了 {result.RemovedCharactersCount} 个孤立角色");
                if (result.RemovedVectorRecordsCount > 0)
                    details.Add($"清理了 {result.RemovedVectorRecordsCount} 个孤立向量记录");
                if (result.RemovedWorldSettingsCount > 0)
                    details.Add($"清理了 {result.RemovedWorldSettingsCount} 个孤立世界设定");
                
                if (details.Count == 0)
                    details.Add("未发现需要清理的数据");
                
                CleanupDetailsListBox.ItemsSource = details;
            }
            else
            {
                CleanupResultText.Text = $"❌ {result.Message}";
                CleanupResultText.Foreground = System.Windows.Media.Brushes.Red;
                CleanupDetailsListBox.ItemsSource = null;
            }
        }
    }
}
